import com.ibm.mq.*;

public class MQIBM {
	private MQQueueManager qMgr;

	private void getConnMQmanager() {
		MQEnvironment.hostname = "localhost";
		MQEnvironment.channel = "c1";
		MQEnvironment.CCSID = 1381;
		MQEnvironment.port = 1414;
//		MQEnvironment.userID = "tuyou";
//		MQEnvironment.password = "1";
		try {
			this.qMgr = new MQQueueManager("qm1");
		} catch (MQException e) {
			e.printStackTrace();
		}
	}

	private void closeConnMQmanager() {
		if (this.qMgr != null)
			try {
				this.qMgr.close();
			} catch (MQException e) {
				e.printStackTrace();
			}
	}

	public void receiveMsg(String queueStr) {
		int openOptions = 49;
		MQQueue queue = null;
		try {
			queue = this.qMgr.accessQueue(queueStr, openOptions, null, null,
					null);

			System.out.println("该队列当前的深度为:" + queue.getCurrentDepth());
			System.out.println("===========================");
			int depth = queue.getCurrentDepth();

			while (depth-- > 0) {
				MQMessage msg = new MQMessage();
				MQGetMessageOptions gmo = new MQGetMessageOptions();
				queue.get(msg, gmo);
				System.out.println("消息的大小为：" + msg.getDataLength());
				System.out.println("消息的内容：\n" + msg.readLine());
				System.out.println("---------------------------");
			}
		} catch (MQException e) {
			e.printStackTrace();

			if (queue != null)
				try {
					queue.close();
				} catch (MQException e1) {
					e1.printStackTrace();
				}
		} catch (Exception e) {
			e.printStackTrace();

			if (queue != null)
				try {
					queue.close();
				} catch (MQException e1) {
					e1.printStackTrace();
				}
		} finally {
			if (queue != null)
				try {
					queue.close();
				} catch (MQException e) {
					e.printStackTrace();
				}
		}
	}

	public static void main(String[] args) {
		MQIBM mm = new MQIBM();
		mm.getConnMQmanager();
		try {
			mm.receiveMsg("q1");
			try {
				Thread.sleep(1000L);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		mm.closeConnMQmanager();
	}
}